<template>
	<view class="page">

		<view class="banner">
			<u--image :src="model1.event.image1" width="750rpx" height="260rpx"></u--image>
		</view>
		<view class="avatar-btn">
			<u-button @tap="upload" text="上传封面"></u-button>
		</view>
		
		

		<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
		<view class="form">
			<u--form labelPosition="top" :model="model1" :labelStyle="{width: '300rpx'}" :rules="rules" ref="uForm">
				<u-form-item label="组局模板" borderBottom @click="history_show = true"
					ref="item1">
					<u--input v-model="historyName" disabled disabledColor="#ffffff" placeholder="选择模板"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				
				<u-form-item label="组局主题" prop="event.theme" :required="true" borderBottom ref="item1">
					<u--input v-model="model1.event.theme" border="none" placeholder="请输入活动主题"></u--input>
				</u-form-item>
				<!-- 				<u-form-item label="价格" prop="event.price" borderBottom ref="item1">
					<u--input type="number" clearable v-model="model1.event.price" border="none"></u--input>
				</u-form-item> -->

				<u-form-item label="价格" prop="event.price" :required="true" borderBottom
					ref="item1">
					<u--input type="number" clearable v-model="model1.event.price" border="none"></u--input>
					
					<!-- 原本是选择模板的，后期改成自由填写 -->
					 <!-- @click="price_show = true" -->
					<!-- <u--input v-model="model1.event.price" disabled disabledColor="#ffffff" placeholder="请选择价格"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon> -->
				</u-form-item>

				<u-form-item label="最少组局女性" prop="event.female_member" :required="true" borderBottom ref="item1">
					<u--input type="number" clearable v-model="model1.event.female_member" border="none"></u--input>
				</u-form-item>
				<u-form-item label="最少成局人数" prop="event.min_member" :required="true" borderBottom ref="item1">
					<u--input type="number" clearable v-model="model1.event.min_member" border="none"></u--input>
				</u-form-item>
				<u-form-item label="最大成局人数" prop="event.sum_member" :required="true" borderBottom ref="item1">
					<u--input type="number" clearable v-model="model1.event.sum_member" border="none"></u--input>
				</u-form-item>

				<u-form-item label="活动标签" prop="tagList" :required="true" borderBottom ref="item1">
					<u-checkbox-group v-model="model1.tagList" shape="square">
						<view style="display: flex;flex-wrap: wrap;">
							<u-checkbox :customStyle="{margin: '5px'}" v-for="(item, index) in checkTagList"
								:key="index" :label="item.name" :name="item.name" :checked="item.checked">
							</u-checkbox>
						</view>
					</u-checkbox-group>
				</u-form-item>




				<u-form-item label="团体限定" prop="grouptagList"  borderBottom ref="item1">
					<u-checkbox-group v-model="model1.grouptagList" shape="square">
						<view style="display: flex;flex-wrap: wrap;">
							<u-checkbox :customStyle="{margin: '5px'}" v-for="(item, index) in group_list"
								:key="index" :label="item.name" :name="item.nid" :checked="item.checked">
							</u-checkbox>
						</view>
					</u-checkbox-group>
				</u-form-item>



				<u-form-item label="活动提供" :required="true" borderBottom ref="item2">
					<u-radio-group @change="status_provide" v-model="default_provide">
						<u-radio :customStyle="{marginRight: '16px'}" v-for="(item, index) in provider_ist" :key="index"
							:label="item.name" :name="item.value" :disabled="item.disabled">
						</u-radio>
					</u-radio-group>
				</u-form-item>
				
				<u-form-item label="联系电话" prop="event.phone" :required="true" borderBottom ref="item1">
					<u--input type="number"  v-model="model1.event.phone" border="none"></u--input>
				</u-form-item>
				
				
				<!-- 				<u-form-item label="首页推荐" prop="radiovalue1" borderBottom ref="item2">
					<u-radio-group v-model="model1.event.recommend">
						<u-radio :customStyle="{marginRight: '16px'}" v-for="(item, index) in recommendList"
							:key="index" :label="item.name" :name="item.value">
						</u-radio>
					</u-radio-group>
				</u-form-item> -->

				<u-form-item label="状态" :required="true" borderBottom ref="item2">
					<u-radio-group @change="statusChange">
						<u-radio :customStyle="{marginRight: '16px'}" v-for="(item, index) in statusList" :key="index"
							:label="item.name" :name="item.value">
						</u-radio>
					</u-radio-group>
				</u-form-item>

				<u-form-item label="活动状态" :required="true" borderBottom ref="item2">
					<u-radio-group @change="eventStatusChange">
						<u-radio :customStyle="{marginRight: '16px'}" v-for="(item, index) in eventStatusList"
							:key="index" :label="item.name" :name="item.value">
						</u-radio>
					</u-radio-group>
				</u-form-item>

				<!-- 			<u-form-item label="简介" :required="true" prop="remark" borderBottom ref="item3">
					<u--textarea placeholder="不低于3个字" v-model="model1.event.remark" count></u--textarea>
				</u-form-item> -->

				<u-form-item label="报名开始" :required="true" prop="event.apply_starttime" borderBottom
					@click="showDatetimePicker(1)" ref="item1">
					<u--input v-model="model1.event.apply_starttime" disabled disabledColor="#ffffff"
						placeholder="请选择报名开始" border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="报名结束" prop="event.apply_endtime" :required="true" borderBottom
					@click="showDatetimePicker(2)" ref="item1">
					<u--input v-model="model1.event.apply_endtime" disabled disabledColor="#ffffff"
						placeholder="请选择报名结束" border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="活动开始" prop="event.starttime" :required="true" borderBottom
					@click="showDatetimePicker(3)" ref="item1">
					<u--input v-model="model1.event.starttime" disabled disabledColor="#ffffff" placeholder="请选择活动开始"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="活动结束" :required="true" prop="event.endtime" borderBottom
					@click="showDatetimePicker(4)" ref="item1">
					<u--input v-model="model1.event.endtime" disabled disabledColor="#ffffff" placeholder="请选择活动结束"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>

				<u-form-item label="活动地址" :required="true" prop="event.address" labelWidth="70">
					<u-input placeholder="点击选择地址" v-model="model1.event.address" @focus="chooseLocation"
						suffixIcon="map-fill" suffixIconStyle="color: #909399">
					</u-input>
				</u-form-item>


				<u-form-item label="活动详情">
					<EditorContext name="content" :html="model1.event.content" @changes="detail_content">
					</EditorContext>
				</u-form-item>

<!-- 				<u-form-item label="活动结束后详情">
					<EditorContext name="finnsh_content" :html="model1.event.finnsh_content" @changes="detail_content">
					</EditorContext>
				</u-form-item> -->

				<u-form-item label="用户须知">
					<EditorContext name="user_notice" :html="model1.event.user_notice" @changes="detail_content">
					</EditorContext>
				</u-form-item>

				<!-- 				<u-form-item  label="用户协议">
					<EditorContext name="user_agreement" :html="model1.event.user_agreement" @changes="detail_content">
					</EditorContext>
				</u-form-item> -->

			</u--form>
		</view>

		<u-button @click="submit" :disabled="submitDisabled" customStyle="background-color: #ffd91d">提交</u-button>

		<u-picker :show="price_show" :columns="priceList" @cancel="pricecancel" @confirm="priceconfirm"></u-picker>
		<u-picker :show="history_show" :columns="historyList" @cancel="historyCancel" @confirm="historyConfirm"></u-picker>
		
		<u-datetime-picker :show="apply_starttime_show" v-model="currDate" mode="datetime" closeOnClickOverlay
			@confirm="confirm" @cancel="cancel" @close="close"></u-datetime-picker>

	</view>
</template>

<script>
	import * as Config from '@/utils/config.js'
	import * as EventApi from '@/api/event.js';
	import EditorContext from '@/components/editor/editor.vue'
	import * as groupApi from '@/api/group.js';
	//这个会报警告↓
	import * as mod_add_default from '@/pages/activity/controller/model/mod_add_default.js'
	export default {
		components: {
			EditorContext: EditorContext
		},
		data() {
            return {
				historyIndex: 0,
				submitDisabled: false,
				currDate: Number(new Date()),
				apply_starttime_show: false,
				price_show: false,
				history_show: false,
				load_show: false,
				default_provide:"第三方",
				model1: {
					event: {
						image1: '',
						remark: '',
						content: '',
						finnsh_content: '',
						user_notice: '',
						user_agreement: '',
						address: ''
					},
					tagList: []
				},
				
				rules: {
					'event.theme': {
						type: 'string',
						required: true,
						max: 30,
						message: '请填写活动主题',
						trigger: ['blur', 'change']
					},
					'event.price': {
						type: 'number',
						required: true,
						message: '请填写价钱',
						trigger: ['blur', 'change']
					},
					'event.female_member': {
						type: 'number',
						required: true,
						max: 8,
						min: 1,
						message: '请填写最少女数',
						trigger: ['blur', 'change']
					},
					'event.min_member': {
						type: 'number',
						required: true,
						max: 8,
						min: 1,
						message: '请填写最少成局人数',
						trigger: ['blur', 'change']
					},
					'event.max_member': {
						type: 'number',
						required: true,
						max: 8,
						min: 1,
						message: '请填写最大成局人数',
						trigger: ['blur', 'change']
					},
					'event.apply_starttime': {
						type: 'string',
						required: true,
						message: '请选择报名开始时间',
						trigger: ['blur', 'change']
					},
					'event.apply_endtime': {
						type: 'string',
						required: true,
						message: '请选择报名结束时间',
						trigger: ['blur', 'change']
					},
					'event.starttime': {
						type: 'string',
						required: true,
						message: '请选择活动开始时间',
						trigger: ['blur', 'change']
					},
					'event.endtime': {
						type: 'string',
						required: true,
						message: '请选择活动结束时间',
						trigger: ['blur', 'change']
					},
					'event.address': {
						type: 'string',
						required: true,
						message: '请选择地址',
						trigger: ['blur', 'change']
					},
				
					tagList: {
						type: 'array',
						min: 1,
						required: true,
						message: '至少选一项',
						trigger: ['change']
					},
				},
				radio: '',
				switchVal: false,
				checkTagList: [],
				group_list: [],
				priceList: [],
				historyName: '无',
				historyList: [],
				historyEvevtList: [],
				
				recommendList: [{
						name: '是',
						value: 0,
						disabled: false,
						checked: false
					},
					{
						name: '否',
						value: 1,
						disabled: false,
						checked: false
					},
				],
				statusList: [{
						name: '发布中',
						value: 1,
						disabled: false,
						checked: false
					},
					{
						name: '未发布',
						value: 2,
						disabled: false,
						checked: false
					}
				],
				provider_ist: [{
						name: '官方',
						value:'官方',
						disabled: true,
						checked: false
					},
					{
						name: '第三方',
						value: '第三方',
						disabled: false,
						checked: false
					}
				],
				eventStatusList: [{
						name: '组局中',
						value: 0,
						disabled: false,
						checked: false
					},
					{
						name: '成局',
						value: 1,
						disabled: false,
						checked: false
					},
					{
						name: '流局',
						value: 2,
						disabled: false,
						checked: false
					},
				],
						 
							
			}
		},
		onLoad() {
			this.getTags()
			this.getPrices()
			this.getHistory_list()
			this.grouplist()
		},
		onShow() {

		},

		methods: {
			bindPickerChange: function(e) {
				console.log('picker发送选择改变，携带值为', e.detail.value)
				this.historyIndex = e.detail.value
			},
			eventStatusChange(e) {
				this.model1.event.event_status = e
			},
			statusChange(e) {
				this.model1.event.status = e
			},
			status_provide(e) {
				this.model1.event.provider = e
			},
			
			detail_content(res) {
				this.model1.event[res.name] = res.html
			},
			// 返回顶部
			toTop() {
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 100,
				});
			},

			showDatetimePicker(index) {
				this.current = index
				this.apply_starttime_show = true
			},

			priceclose() {

				this.price_show = false
			},
			priceconfirm(e) {
				// console.log('confirm', e);
				this.price_show = false
				let s = e.value[0].split('：');
				this.model1.event.price = Number(s[1])
			},
			pricecancel() {
				// console.log('cancel');
				this.price_show = false
			},
			historyConfirm(e) {
				this.history_show = false

				uni.navigateTo({
					url: "/pages/activity/edit?id="+this.historyEvevtList[e.indexs[0]].nid + '&ishistory=history'
				})
				
				this.historyName = e.value[0]
			},
			historyCancel(){
				this.history_show = false
			},

			close() {
				this.apply_starttime_show = false
			},
			cancel() {
				this.apply_starttime_show = false
			},
			confirm(e) {
				// this[`show${this.current}`] = false
				this.apply_starttime_show = false
				let arr = ['apply_starttime', 'apply_endtime', 'starttime', 'endtime'];
				this.model1.event[arr[this.current - 1]] = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM')

			},

			checkboxClick(index) {
				let s = this.model1.event.tag[index].select
				this.model1.event.tag[index].select = s == 0 ? 0 : 1
			},

			getPrices() {
				EventApi.pricemod().then(res => {

					// this.priceList = res.info
					let list = [];
					res.info.forEach(e => {
						list.push(e.name + '：' + e.price)
					})

					this.priceList.push(list)

				})
			},
			getHistory_list() {
				EventApi.history_list().then(res => {
					this.historyEvevtList = res.info
					
					let list = [];
					res.info.forEach(e => {
						list.push(e.theme)
					})
					
					this.historyList.push(list)
					
				})
			},

//获取活动的标签？
			getTags() {
				EventApi.event_author().then(res => {
					
					let list = res.data.event_author.split(',')
					
					console.log("res".res)
					console.log("list".list)
					
					list.forEach(e => {
						this.checkTagList.push({
							name: e,
							checked: false
						})
					})
					
					console.log("res.data.super_leader",res.data.super_leader)
					 
					
					//这里已经拿到了是否超级管理员的数据，所以直接在这个函数去处理是否可以开官方局
					if(res.data.super_leader == '是' )
					{
						this.provider_ist[0].disabled=false;
						console.log("this.provider_ist",this.provider_ist)
					}
					
			
			
				})
			},
			
			
			//获取所有的团体
			grouplist() {
				console.log("grouplist")
				uni.request({
					url: Config.baseUrl + '/api/miniapp/group/get_group_list.php',
					data: {
						page: this.page,
						Authorization: Config.getStorageUserId(),
					},
					success: (res) => {
						this.group_list = res.data.info
						console.log("this.group_list", this.group_list)
					}
				});
			
				
			},
			
			
			
			submit() {

				if (!this.model1.event.image1) {
					uni.$u.toast('请上传封面')
					return false
				}
				this.$refs.uForm.validate().then(res => {
				
					let group = "";
					this.model1.grouptagList.forEach(e => {
						console.log("e",e)
						group += e + ','
					})
					
					this.model1.event.grouptag = group.substr(0, group.length - 1)
					
					console.log("this.model1.event",this.model1.event)
					
					
					let tag = "";
					this.model1.tagList.forEach(e => {
						tag += e + ','
					})

					this.model1.event.tag = tag.substr(0, tag.length - 1)
					
					
					if(!this.model1.event.provider)
					{
						this.model1.event.provider = "第三方"
					}
					

					this.submitDisabled = true
					
					EventApi.add(this.model1.event).then(res => {
						uni.$u.toast(res.info)
						if (res.status == 200) {
							console.log("提交成功")
							setTimeout(() => {
								uni.redirectTo({
									url: '/pages/activity/manage'
								})
							}, 1000)
						} else {
							this.submitDisabled = false
						}

					})
				}).catch(errors => {
					uni.$u.toast('请正确填写资料')

				})
			},

			chooseLocation() {
				console.log('详细地址')
				let self = this;
				uni.chooseLocation({
					success: (res) => {
						self.model1.event.address = res.address;
						self.model1.event.location = res.latitude + ',' + res.longitude;
						console.log('位置名称：' + res.name);
						console.log('详细地址：' + res.address);
						console.log('纬度：' + res.latitude);
						console.log('经度：' + res.longitude);
					},
					fail: () => {
						// 如果用uni.chooseLocation没有获取到地理位置，则需要获取当前的授权信息，判断是否有地理授权信息
						self.model1.detail = '详细地址'
						uni.getSetting({
							success: (res) => {
								console.log(res);
								var status = res.authSetting;
								if (!status['scope.userLocation']) {
									// 如果授权信息中没有地理位置的授权，则需要弹窗提示用户需要授权地理信息
									uni.showModal({
										title: "是否授权当前位置",
										content: "需要获取您的地理位置，请确认授权，否则地图功能将无法使用",
										success: (tip) => {
											if (tip.confirm) {
												// 如果用户同意授权地理信息，则打开授权设置页面，判断用户的操作
												uni.openSetting({
													success: (data) => {
														// 如果用户授权了地理信息在，则提示授权成功
														if (data
															.authSetting[
																'scope.userLocation'
															] === true
														) {
															uni.showToast({
																title: "授权成功",
																icon: "success",
																duration: 1000
															})
															// 授权成功后，然后再次chooseLocation获取信息
															uni.chooseLocation({
																success: (
																	res
																) => {
																	self.model1
																		.event
																		.address =
																		res
																		.address;
																	self.model1
																		.event
																		.location =
																		res
																		.latitude +
																		',' +
																		res
																		.longitude;
																	console
																		.log(
																			'位置名称：' +
																			res
																			.name
																		);
																	console
																		.log(
																			'详细地址：' +
																			res
																			.address
																		);
																	console
																		.log(
																			'纬度：' +
																			res
																			.latitude
																		);
																	console
																		.log(
																			'经度：' +
																			res
																			.longitude
																		);
																}
															})
														} else {
															uni.showToast({
																title: "授权失败",
																icon: "none",
																duration: 1000
															})
														}
													}
												})
											}
										}
									})
								}
							},
							fail: (res) => {
								uni.showToast({
									title: "调用授权窗口失败",
									icon: "none",
									duration: 1000
								})
							}
						})
					}
				});
			},

			upload() {
				let that = this;
				uni.chooseImage({
					success: (chooseImageRes) => {

						uni.uploadFile({
							header: {
								Authorization: Config.getStorageUserId(),
							},
							url: Config.baseUrl +
								'/api/miniapp/event.php?act=upload_img',
							filePath: chooseImageRes.tempFilePaths[0],
							name: 'file',
							success: (uploadFileRes) => {
								let d = JSON.parse(uploadFileRes.data)
								if (d.status == 200) {
									that.model1.event.image1 = d.url
								} else {
									uni.$u.toast('上传失败')
								}
							}
						});
					}
				});
			},

		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.uForm.setRules(this.rules)
		},
	}
</script>

<style scoped lang="scss">
	@import url("asset/style.css");
</style>